package com.example.myserver;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private Button kaishi,jieshu,jieshuf,next;
    private TextView txt;
//    保持所启的Service的
    private MyService.MyBinder binder;
    private boolean flag;
    private int num =0;
//    定义一个ServiceConnection对象；
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyService.MyBinder) service;
            Log.i("TAG", "onServiceConnected: ");
            Log.i("TAG", name.toString());
            Log.i("TAG", service.toString());
            flag =true;
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("TAG", "onServiceDisconnected: ");
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        kaishi = findViewById(R.id.kaishi);
        jieshu = findViewById(R.id.jieshu);
        jieshuf  =findViewById(R.id.jieshuf);
        txt = findViewById(R.id.txt);
        txt.setText(String.valueOf(num));
        next = findViewById(R.id.next);
        next.setOnClickListener(v->startActivity(new Intent(MainActivity.this,MainActivity2.class)));
        Intent intent  = new Intent(this,MyService.class); //传入本类类名和要调起来的类类名
        kaishi.setOnClickListener(
                v -> bindService(intent,connection,BIND_AUTO_CREATE)// 通过bindserver来绑定上服务
                 );
            jieshu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (flag) {
                        unbindService(connection); //通过unbindService来解除服务
                        flag =false;
                    }
                    Toast.makeText(MainActivity.this, "sadf", Toast.LENGTH_SHORT).show();
                }
            });
        jieshuf.setOnClickListener(v -> Toast.makeText(MainActivity.this, "service的count值"+binder.getCount(), Toast.LENGTH_SHORT).show());
    }
}